<template>
  <div>
    <header-toobar>
      <a-button style="margin-left: 6px;" size="small" v-func:USER0027 type="primary" icon="plus" @click="() =>{this.batchCreateUser()}">批量生成
      </a-button>
      <a-button style="margin-left: 6px;" size="small" v-func:USER0015 type="primary" icon="plus" @click="() =>{this.openSystemPrivilegePage()}">
        系统级权限分配
      </a-button>
      <a-button style="margin-left: 6px;" size="small" v-func:USER0019 type="primary" icon="plus" @click="() =>{this.openRoleModel()}">角色分配
      </a-button>
      <a-tooltip v-func:USER0021 placement="top" title="单独授权角色之外的功能权限">
        <a-button style="margin-left: 6px;" size="small" type="primary" icon="plus" @click="() =>{this.openUserRouterFuncModel()}">
          资源分配
        </a-button>
      </a-tooltip>

      <a-tooltip v-func:USER0026 placement="top" title="单独授权角色之外的节点权限">
        <a-button style="margin-left: 6px;" size="small" type="primary" icon="plus" @click="() =>{this.openUserFlowNodeModel()}">
          流程节点分配
        </a-button>
      </a-tooltip>
      <a-button v-func:USER0020 style="margin-left: 6px;" size="small" type="primary" icon="plus" @click="() =>{this.openUserOrgModel()}">组织分配
      </a-button>
      <a-button v-func:USER0001 style="margin-left: 6px" size="small" type="primary" icon="user-add" @click="() =>{this.openAddUser()}">创建</a-button>
      <a-button v-func:USER0002 style="margin-left: 6px;" size="small" type="primary" icon="edit" @click="() =>{this.openEditUser()}">编辑</a-button>
      <a-button v-func:USER0008 style="margin-left: 6px" size="small" type="danger" icon="user-delete" @click="() =>{this.deleteUser()}">删除
      </a-button>
    </header-toobar>
    <zh-row :span="24" :gutter="[16,16]">
      <zh-col>
        <zh-card title="查询条件">
        <zh-form ref="userQueryFrom" :model="queryParam">
          <zh-input prop="userName" label="用户名" placeholder="支持模糊查询" v-model="queryParam.userName"></zh-input>
          <zh-input prop="fullName" label="姓名" placeholder="支持模糊查询" v-model="queryParam.fullName"></zh-input>

          <template v-if="advanced">
            <zh-input prop="cellphone" label="手机" placeholder="只能精确查找" v-model="queryParam.cellphone"></zh-input>
            <zh-input prop="orgIds" type="tree" label="所属组织" mode="multiple" placeholder="支持多选"
                      treeNodeFilterProp="title"
                      allowClear
                      multiple
                      treeDefaultExpandAll
                      v-model="queryParam.orgIds"
                      :treeData="orgSelectTreeData"
                      >
            </zh-input>
            <zh-input prop="status" type="select" label="状态" placeholder="单选" allowClear :options="statusData"
                      v-model="queryParam.status"></zh-input>
            <zh-input :disabled="userTypeDisabled" prop="userTypeList" type="select" label="用户类型" mode="multiple" placeholder="支持多选" allowClear
                      :options="selectData.userType" v-model="queryParam.userTypeList"></zh-input>
          </template>
          <zh-form-query v-model="advanced" @queryClick="findUserListBtn"></zh-form-query>
        </zh-form>
        </zh-card>
      </zh-col>
      <zh-col>
        <zh-table :shadow="true" ref="userListTable" title="用户列表" row-id="userId" :url="tableUrl" :columns="tableColumn"
                  @radio-change="radioChangeEvent" :radio-config="{ trigger: 'row'}"  :disabled="false">
          <template #status_edit="{ row }">
            <zh-input type="switch" :formflag="false" v-model="row.status" @change="onStatusChange(row)"
                      checked-children="启用" un-checked-children="禁用"></zh-input>
          </template>
        </zh-table>
      </zh-col>
    </zh-row>
      <a-modal
          :title="modalTitle"
          centered
          style="top: 20px;"
          width="85%"
          destroyOnClose
          v-model="visible"
          cancelText="关闭"
          okText="保存"
          @ok="saveUser"
          @cancel="cancelUser"
      >
        <user-form ref="userPage" :userInfo="userInfo"/>
      </a-modal>
      <a-modal
          title="系统级权限授权"
          centered
          width="300"
          destroyOnClose
          v-model="sysPrivilegeVisible"
      >
        <template slot="footer">
          <a-button key="submit" type="primary" @click="closeSysPrivilege">
            确定
          </a-button>
        </template>
        <system-permission-form ref="userSystemPrivilegePage" :userInfo="selectRow"/>
      </a-modal>
      <a-modal
          title="角色授权"
          centered
          style="top: 10px;"
          width="80%"
          destroyOnClose
          v-model="roleVisible"
          cancelText="关闭"
          okText="保存"
          @ok="saveRole"
      >
        <role-transfer-form ref="roleTransferPage"/>
      </a-modal>
      <a-modal
          title="组织授权"
          centered
          style="top: 10px;"
          width="450px"
          destroyOnClose
          v-model="roleOrgVisible"
          @ok="saveOrg"
          cancelText="关闭"
          okText="保存"
      >
        <org-tree-form ref="orgTreePage" :userId="userId"/>
      </a-modal>
      <a-modal
          title="资源授权"
          centered
          style="top: 10px;"
          width="450px"
          destroyOnClose
          v-model="roleRouterFuncVisible"
          @ok="saveRouterFunc"
          cancelText="关闭"
          okText="保存"
      >
        <router-func-tree-form ref="routerFuncTreePage" :userId="userId"/>
      </a-modal>

      <a-modal
          title="流程节点授权"
          centered
          style="top: 10px;"
          width="450px"
          destroyOnClose
          v-model="userFlowNodeVisible"
          @ok="saveFlowNode"
          cancelText="关闭"
          okText="保存"
      >
        <flow-node-tree-form ref="flowNodeTreePage" :userId="userId"/>
      </a-modal>
   <a-back-top>
      <div class="ant-back-top-inner">
        UP
      </div>
    </a-back-top>
  </div>
</template>

<script>
import {
  addUser,
  createImpUser,
  deleteUser,
  editUser,
  editUserStatus,
  getBatchDict,
  getOrgSelectTree,
  getUserList,
  getUserRoleInfo,
  resetPassword,
  saveUserFlowNode,
  saveUserOrg,
  saveUserRole,
  saveUserRouterFunc
} from "@/services/system/api"
import HeaderToobar from '@/components/HeaderToobar'
import modal from 'ant-design-vue/es/modal'
import UserForm from '@/pages/system/form/UserForm'
import RoleTransferForm from '@/pages/system/form/RoleTransferForm'
import SystemPermissionForm from '@/pages/system/form/SystemPermissionForm'
import OrgTreeForm from '@/pages/system/form/OrgTreeForm'
import RouterFuncTreeForm from '@/pages/system/form/RouterFuncTreeForm'

import FlowNodeTreeForm from '@/pages/system/form/FlowNodeTreeForm'
import moment from 'moment'

export default {
  name: 'UserManager',
  components: {
    HeaderToobar,
    UserForm,
    SystemPermissionForm,
    RoleTransferForm,
    OrgTreeForm,
    RouterFuncTreeForm,

    FlowNodeTreeForm
  },
  data() {
    return {
      description: '用户信息管理',
      selectData: {},
      orgSelectTreeData: [],
      visible: false,
      userTypeDisabled:false,
      sysPrivilegeVisible: false,
      // 角色授权
      roleVisible: false,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 表头
      tableColumn: [
        {
          type: 'radio', width: 40, fixed: 'left', align: 'center', slots: {
            header: () => {
              return [<a-tooltip placement="top" title="取消选择">
                <a-icon type="stop" theme="twoTone" onClick={this.clearRadioRowEevnt}/>
              </a-tooltip>]
            }
          }
        },
        {type: 'seq', width: 60, fixed: 'left', align: 'center', title: '序号'},
        {field: 'userName', title: '用户名', fixed: 'left', align: 'center', width: 150},
        {field: 'fullName', title: '姓名', align: 'center', fixed: 'left', width: 150},
        {field: 'userId', title: '用户Id', visible: false, align: 'center', width: 150},
        {
          field: 'status', title: '状态', align: 'center', editRender: {}, slots: {
            // 使用插槽模板渲染
            default: 'status_edit',
            edit:'status_edit'
          }, width: 80
        },
        {
          field: 'resetPassword', title: '重置密码', align: 'center', width: 80, slots: {
            default: ({row}) => {
              let flag=row.userType==='20'
              return [<a-tooltip placement="top" title="点击重置密码">
                <a-button type="danger" disabled ={flag}  block onClick={() => this.resetPasswordEevnt(row.userId)}>重置</a-button>
              </a-tooltip>]
            }
          }
        },
        {field: 'email', title: '电子邮箱', align: 'center', showOverflow: true, width: 150},
        {field: 'cellphone', title: '手机', align: 'center', width: 100},
        {field: 'idcard', title: '身份证', align: 'center', width: 150},
        {field: 'userType', title: '用户类型key', visible: false, align: 'center', width: 150},
        {field: 'userTypeName', title: '用户类型', align: 'center', width: 150},
        {field: 'userIp', title: '使用用户ip', align: 'center', showOverflow: true, width: 200},
        {field: 'orderNo', title: '顺序', align: 'center', width: 50},
        {field: 'nikeName', title: '昵称', align: 'center', width: 150},
        {field: 'sex', title: '性别', visible: false, align: 'center', width: 50},
        {field: 'sexName', title: '性别', align: 'center', width: 50},
        {field: 'birthday', title: '出生日期', align: 'center', width: 100},
        {field: 'address', title: '地址', align: 'center', showOverflow: true, width: 200},
        {field: 'officePhone', title: '办公室电话', align: 'center', width: 100},
        {field: 'shortPhone', title: '短号', align: 'center', width: 60},
        {field: 'orgId', title: '所属组织', visible: false, align: 'center', showOverflow: true, width: 150},
        {field: 'orgName', title: '所属组织', align: 'center', showOverflow: true, width: 150},
        {field: 'clientId', title: '所属应用', visible: false, align: 'center', showOverflow: true, width: 150},
        {field: 'regdate', title: '创建日期', align: 'center', width: 80},
        {field: 'remarks', title: '备注', align: 'center', showOverflow: true, width: 250}
      ],
      tableData: [],
      selectRow: null,
      modalTitle: '操作',
      userId: null,
      roleOrgVisible: false,
      roleRouterFuncVisible: false,
      userFlowNodeVisible: false,
      opUserId: null,
      statusData: [{dictKey: '1', dictValue: '启用'}, {dictKey: '0', dictValue: '禁用'}],
      tableUrl: getUserList,
      userInfo:{},
      userType:null
    }
  },
  created() {
    //获取路由配置中param1参数
    let meta=this.$router.currentRoute.meta
    if(meta&&meta.query){
        if(meta.query.userType){
            this.queryParam.userType=meta.query.userType
            this.userType=meta.query.userType
            let userTypeList=[]
            userTypeList.push(meta.query.userType)
            this.queryParam.userTypeList=userTypeList
            this.userTypeDisabled=true
        }
       
    }
    // 数据初始化
    // 数据字典初始化
    const params = {}
    params.dictFields = 'userType'
    this.$http.post(getBatchDict, params).then(res => {
      this.selectData = res.result
    })
    // 下拉组织树初始化
    this.$http.post(getOrgSelectTree, params).then(res => {
      this.orgSelectTreeData = res.result
    })
    let userInfo = this.$store.state.user.userInfo;
    this.opUserId = userInfo.userId;
    // 初始化人员列表
    this.$nextTick(() => {
        this.findUserList()
    })
  },
  methods: {
    moment,
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    searchOrgClick(row){
        this.form.orgId=row.orgId
    },
    radioChangeEvent({row}) {
      this.selectRow = row
      this.userId = row.userId
      console.log('单选事件')
    },
    clearRadioRowEevnt() {
      this.selectRow = null
      this.userId = null
      this.$refs.userListTable.clearRadioRow()
    },
    // 重置密码
    resetPasswordEevnt(userId) {
      const params = {}
      if (userId) {
        if (this.opUserId == userId) {
          modal.warn({title: '提示', content: '不能对自己进行操作'})
          return
        }
        params.userId = userId
        this.$http.post(resetPassword, params).then((res) => {
          modal.info({title: '成功提示', content: '重置成功！密码为'+res.result})
        }).catch(() => {
        })
      } else {
        modal.error({title: '错误提示', content: '程序异常，未传入用户Id字段'})
      }
    },
    // 用户列表查询
    findUserListBtn() {
      this.findUserList()
    },
    findUserList() {
      this.$refs.userListTable.query(this.queryParam)
    },
    refreshList() {
      this.$refs.userListTable.refresh(this.queryParam)
    },
    // 启用/禁用用户
    onStatusChange(row) {
      if (this.opUserId === row.userId) {
        row.status=!row.status
        modal.warn({title: '提示', content: '不能对自己进行操作'})
        return
      }
      const params = {}
      params.userId = row.userId
      params.status = row.status
      let text="禁用"
      if(row.status==='1'){
          text='启用'
      }
      this.$http.post(editUserStatus, params).then(() => {
         modal.info({title: '成功提示', content: text + '成功'})
      }).catch(() => {
          row.status=!params.status
      })
      
    },
    batchCreateUser() {
      const params = {}
      setTimeout(() => {
        this.$http.post(createImpUser, params).then((res) => {
          modal.info({title: '成功提示', content: '成功生成' + res.result + '个用户'})
        }).catch(() => {
        })
      }, 200)
    },
    openSystemPrivilegePage() {
      if (this.selectRow) {
        if (this.opUserId == this.selectRow.userId) {
          modal.warn({title: '提示', content: '不能对自己进行操作'})
          return
        }
        this.sysPrivilegeVisible = true
      } else {
        modal.warn({title: '提示', content: '请先选择需要修改的数据'})
      }
    },
    openAddUser() {
      this.clearRadioRowEevnt()
      let userInfo={}
      userInfo.userType=this.userType
      this.userInfo=userInfo
      this.modalTitle = '新增用户信息'
      this.visible = true
    },
    openEditUser() {
      if (this.selectRow) {
        let userInfo={}
        userInfo.userType=this.selectRow.userType
        userInfo.userId=this.selectRow.userId
        this.userInfo=userInfo
        this.modalTitle = '修改用户信息'
        this.visible = true
      } else {
        modal.warn({title: '提示', content: '请先选择需要修改的数据'})
      }
    },
    closeSysPrivilege() {
      this.sysPrivilegeVisible = false
    },
    saveUser() {
        const {$refs: {userPage}} = this
      if (userPage.checkForm()) {
        const userInfo = userPage.form
        if (userInfo.userId) {
          setTimeout(() => {
            this.$http.post(editUser, userInfo).then((res) => {
              modal.info({title: '成功提示', content: '修改成功'})
              this.visible = false
              let row = res.result
              this.$refs.userListTable.updateRow(row)
              this.selectRow = row
              this.userId = row.userId
              this.$refs.userListTable.setRadioRow(row)
              this.$refs.userListTable.setCurrentRow(row)
            }).catch(() => {
                this.visible = true
            })
          }, 200)
        } else {
          setTimeout(() => {
            this.$http.post(addUser, userInfo).then((res) => {
              modal.info({title: '成功提示', content: '新增成功'})
              this.visible = false
              this.queryParam.userName = res.result.userName
              this.findUserList()
            }).catch(() => {
                this.visible = true
            })
          }, 200)
        }
      }
    },
    cancelUser() {
      const user = this.selectRow
      if (user) {
        const data = [...this.tableData]
        if (user.status === '1') {
          user.status = '1'
        } else {
          user.status = '0'
        }
        data.forEach((item, index, arr) => {
          if (item.userId === user.userId) {
            arr.splice(index, 1, user)
            return item
          }
        })
        this.tableData = data
      }
      this.visible = false
    },
    deleteUser() {
      if (this.selectRow) {
        const params = {}
        params.userId = this.selectRow.userId
        setTimeout(() => {
          this.$http.post(deleteUser, params).then(() => {
            modal.info({title: '成功提示', content: '删除用户成功'})
            this.findUserList()
          }).catch(() => {
          })
        }, 100)
      } else {
        modal.warn({title: '提示', content: '请先选择需要删除的数据'})
      }
    },
    openRoleModel() {
      if (this.selectRow) {
        if (this.opUserId == this.selectRow.userId) {
          modal.warn({title: '提示', content: '不能对自己进行操作'})
          return
        }
        const params = {}
        params.userId = this.selectRow.userId
        this.roleVisible = true
        setTimeout(() => {
          this.$http.post(getUserRoleInfo, params).then((res) => {
            this.$refs.roleTransferPage.setDataSource(res.result.roleList)
            this.$refs.roleTransferPage.setTargetKeys(res.result.targetKeys)
          }).catch(() => {
          })
        }, 50)
      } else {
        modal.warn({title: '提示', content: '请先选择需要授权的数据'})
      }
    },
    saveRole() {
      if (this.selectRow) {
        const checkedRoles = this.$refs.roleTransferPage.targetRows
        const userId = this.selectRow.userId
        const params = {}
        params.userId = userId
        params.roleFixedVOList = checkedRoles
        setTimeout(() => {
          this.$http.post(saveUserRole, params).then(() => {
            modal.info({title: '成功提示', content: '授权成功'})
            this.roleVisible = false
          }).catch(() => {
          })
        }, 50)
      } else {
        modal.warn({title: '提示', content: '请先选择需要授权的数据'})
      }
    },
    openUserOrgModel() {
      // 打开组织授权页面
      if (this.userId) {
        if (this.opUserId == this.userId) {
          modal.warn({title: '提示', content: '不能对自己进行操作'})
          return
        }
        this.roleOrgVisible = true
      } else {
        modal.warn({title: '提示', content: '请先选择需要操作的用户'})
      }
    },
    saveOrg() {
      if (this.userId) {
        const checkedObject = this.$refs.orgTreePage.checkedOrgKeys
        const params = {}
        if (checkedObject.checked) {
          const checkedkeys = checkedObject.checked;
          params.userOrgIds = checkedkeys
        } else {
          params.userOrgIds = checkedObject
        }
        params.userId = this.userId
        setTimeout(() => {
          this.$http.post(saveUserOrg, params).then(() => {
            modal.info({title: '成功提示', content: '授权成功'})
            this.roleOrgVisible = false
          }).catch(() => {
          })
        }, 10)
      } else {
        modal.warn({title: '提示', content: '请先选择需要操作的用户'})
      }
    },
    openUserRouterFuncModel() {
      // 打开资源授权页面
      if (this.userId) {
        if (this.opUserId == this.userId) {
          modal.warn({title: '提示', content: '不能对自己进行操作'})
          return
        }
        this.roleRouterFuncVisible = true
      } else {
        modal.warn({title: '提示', content: '请先选择需要操作的用户'})
      }
    },
    saveRouterFunc() {
      if (this.userId) {
        const checkedkeys = this.$refs.routerFuncTreePage.checkedKeys
        const params = {}
        if (Array.isArray(checkedkeys)) {
          params.objectIds = checkedkeys
        } else {
          params.objectIds = checkedkeys.checked
        }
        params.userId = this.userId
        setTimeout(() => {
          this.$http.post(saveUserRouterFunc, params).then(() => {
            modal.info({title: '成功提示', content: '授权成功'})
            this.roleRouterFuncVisible = false
          }).catch(() => {
          })
        }, 10)
      } else {
        modal.warn({title: '提示', content: '请先选择需要操作的用户'})
      }
    },
    clearAll() {
      this.queryParam = {}
      this.findUserList()
      setTimeout(() => {
        this.clearRadioRowEevnt()
        this.$refs.userListTable.clearSelection()
        this.$refs.userListTable.clearSelectReserve()
      }, 50)
    },

    openUserFlowNodeModel() {
      // 打开节点授权页面
      if (this.userId) {
        if (this.opUserId == this.userId) {
          modal.warn({title: '提示', content: '不能对自己进行操作'})
          return
        }
        this.userFlowNodeVisible = true
      } else {
        modal.warn({title: '提示', content: '请先选择需要操作的用户'})
      }
    },

    //保存用户节点授权数据
    saveFlowNode() {
      if (this.userId) {
        const checkedkeys = this.$refs.flowNodeTreePage.checkedKeys
        const params = {}
        if (Array.isArray(checkedkeys)) {
          params.objectIds = checkedkeys
        } else {
          params.objectIds = checkedkeys.checked
        }
        params.userId = this.userId
        setTimeout(() => {
          this.$http.post(saveUserFlowNode, params).then(() => {
            modal.info({title: '成功提示', content: '授权成功'})
            this.userFlowNodeVisible = false
          }).catch(() => {
          })
        }, 10)
      } else {
        modal.warn({title: '提示', content: '请先选择需要操作的角色'})
      }
    }
  },
  watch: {
    /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
  }
}
</script>
